/**
 * 任务队列管理器
 * 用于管理异步任务的状态、进度和结果
 */

// 任务状态枚举
export const TaskStatus = {
  PENDING: "pending", // 等待中
  RUNNING: "running", // 运行中
  COMPLETED: "completed", // 已完成
  FAILED: "failed", // 失败
  CANCELLED: "cancelled", // 已取消
  PAUSED: "paused", // 已暂停
};

// 任务类型枚举
export const TaskType = {
  DOWNLOAD: "download", // 下载任务
  UPLOAD: "upload", // 上传任务
  DELETE: "delete", // 删除任务
  RENAME: "rename", // 重命名任务
  CREATE_FOLDER: "create_folder", // 创建文件夹
  MOVE: "move", // 移动任务
  COPY: "copy", // 复制任务
  OFFLINE_DOWNLOAD: "offline_download", // 离线下载任务
};

// 任务优先级枚举
export const TaskPriority = {
  LOW: 1,
  NORMAL: 2,
  HIGH: 3,
  URGENT: 4,
};

/**
 * 任务类
 */
class Task {
  constructor(id, type, data, priority = TaskPriority.NORMAL) {
    this.id = id;
    this.type = type;
    this.data = data;
    this.priority = priority;
    this.status = TaskStatus.PENDING;
    this.progress = 0; // 0-100
    this.result = null;
    this.error = null;
    this.createdAt = new Date();
    this.startedAt = null;
    this.completedAt = null;
    this.retryCount = 0;
    this.maxRetries = 3;
    this.cancelled = false;
    this.paused = false;
  }

  // 开始任务
  start() {
    this.status = TaskStatus.RUNNING;
    this.startedAt = new Date();
    this.paused = false;
  }

  // 完成任务
  complete(result) {
    this.status = TaskStatus.COMPLETED;
    this.result = result;
    this.progress = 100;
    this.completedAt = new Date();
  }

  // 任务失败
  fail(error) {
    this.status = TaskStatus.FAILED;
    this.error = error;
    this.completedAt = new Date();
  }

  // 取消任务
  cancel() {
    this.status = TaskStatus.CANCELLED;
    this.cancelled = true;
    this.completedAt = new Date();
  }

  // 暂停任务
  pause() {
    this.status = TaskStatus.PAUSED;
    this.paused = true;
  }

  // 恢复任务
  resume() {
    if (this.status === TaskStatus.PAUSED) {
      this.status = TaskStatus.RUNNING;
      this.paused = false;
    }
  }

  // 更新进度
  updateProgress(progress) {
    this.progress = Math.max(0, Math.min(100, progress));
  }

  // 重试任务
  retry() {
    if (this.retryCount < this.maxRetries) {
      this.retryCount++;
      this.status = TaskStatus.PENDING;
      this.error = null;
      this.startedAt = null;
      this.completedAt = null;
      return true;
    }
    return false;
  }

  // 获取任务持续时间
  getDuration() {
    if (!this.startedAt) return 0;
    const endTime = this.completedAt || new Date();
    return endTime - this.startedAt;
  }

  // 获取任务信息摘要
  getSummary() {
    return {
      id: this.id,
      type: this.type,
      status: this.status,
      progress: this.progress,
      priority: this.priority,
      createdAt: this.createdAt,
      duration: this.getDuration(),
      retryCount: this.retryCount,
      error: this.error?.message || null,
    };
  }
}

/**
 * 任务队列管理器
 */
class TaskQueue {
  constructor() {
    this.tasks = new Map();
    this.running = false;
    this.maxConcurrent = 3; // 最大并发任务数
    this.currentRunning = 0;
    this.eventListeners = new Map();
  }

  // 生成唯一任务ID
  generateTaskId() {
    return `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  // 添加任务
  addTask(type, data, priority = TaskPriority.NORMAL) {
    const taskId = this.generateTaskId();
    const task = new Task(taskId, type, data, priority);

    this.tasks.set(taskId, task);
    this.emit("taskAdded", task);

    // 如果队列正在运行，尝试启动新任务
    if (this.running) {
      this.processNextTask();
    }

    return taskId;
  }

  // 获取任务
  getTask(taskId) {
    return this.tasks.get(taskId);
  }

  // 获取所有任务
  getAllTasks() {
    return Array.from(this.tasks.values());
  }

  // 获取任务列表（按状态过滤）
  getTasksByStatus(status) {
    return this.getAllTasks().filter((task) => task.status === status);
  }

  // 获取任务列表（按类型过滤）
  getTasksByType(type) {
    return this.getAllTasks().filter((task) => task.type === type);
  }

  // 删除任务
  removeTask(taskId) {
    const task = this.tasks.get(taskId);
    if (task && task.status === TaskStatus.PENDING) {
      this.tasks.delete(taskId);
      this.emit("taskRemoved", task);
      return true;
    }
    return false;
  }

  // 取消任务
  cancelTask(taskId) {
    const task = this.tasks.get(taskId);
    if (task) {
      task.cancel();
      this.emit("taskCancelled", task);
      this.processNextTask();
      return true;
    }
    return false;
  }

  // 暂停任务
  pauseTask(taskId) {
    const task = this.tasks.get(taskId);
    if (task && task.status === TaskStatus.RUNNING) {
      task.pause();
      this.emit("taskPaused", task);
      this.currentRunning--;
      this.processNextTask();
      return true;
    }
    return false;
  }

  // 恢复任务
  resumeTask(taskId) {
    const task = this.tasks.get(taskId);
    if (task && task.status === TaskStatus.PAUSED) {
      task.resume();
      this.emit("taskResumed", task);
      this.processNextTask();
      return true;
    }
    return false;
  }

  // 重试任务
  retryTask(taskId) {
    const task = this.tasks.get(taskId);
    if (task && task.status === TaskStatus.FAILED) {
      if (task.retry()) {
        this.emit("taskRetried", task);
        this.processNextTask();
        return true;
      }
    }
    return false;
  }

  // 清空已完成的任务
  clearCompletedTasks() {
    const completedTasks = this.getTasksByStatus(TaskStatus.COMPLETED);
    const failedTasks = this.getTasksByStatus(TaskStatus.FAILED);
    const cancelledTasks = this.getTasksByStatus(TaskStatus.CANCELLED);

    [...completedTasks, ...failedTasks, ...cancelledTasks].forEach((task) => {
      this.tasks.delete(task.id);
    });

    this.emit("tasksCleared", {
      completed: completedTasks.length,
      failed: failedTasks.length,
      cancelled: cancelledTasks.length,
    });
  }

  // 启动队列
  start() {
    if (!this.running) {
      this.running = true;
      this.emit("queueStarted");
      this.processNextTask();
    }
  }

  // 停止队列
  stop() {
    this.running = false;
    this.emit("queueStopped");
  }

  // 处理下一个任务
  async processNextTask() {
    if (!this.running || this.currentRunning >= this.maxConcurrent) {
      return;
    }

    // 获取待处理的任务（按优先级排序）
    const pendingTasks = this.getTasksByStatus(TaskStatus.PENDING);
    if (pendingTasks.length === 0) {
      return;
    }

    // 按优先级排序
    pendingTasks.sort((a, b) => b.priority - a.priority);

    const task = pendingTasks[0];
    this.currentRunning++;

    try {
      task.start();
      this.emit("taskStarted", task);

      // 执行任务
      const result = await this.executeTask(task);

      if (task.cancelled) {
        return;
      }

      task.complete(result);
      this.emit("taskCompleted", task);
    } catch (error) {
      if (task.cancelled) {
        return;
      }

      task.fail(error);
      this.emit("taskFailed", task);
    } finally {
      this.currentRunning--;
      this.processNextTask();
    }
  }

  // 执行具体任务
  async executeTask(task) {
    switch (task.type) {
      case TaskType.DOWNLOAD:
        return await this.executeDownloadTask(task);
      case TaskType.UPLOAD:
        return await this.executeUploadTask(task);
      case TaskType.DELETE:
        return await this.executeDeleteTask(task);
      case TaskType.RENAME:
        return await this.executeRenameTask(task);
      case TaskType.CREATE_FOLDER:
        return await this.executeCreateFolderTask(task);
      case TaskType.MOVE:
        return await this.executeMoveTask(task);
      case TaskType.COPY:
        return await this.executeCopyTask(task);
      case TaskType.OFFLINE_DOWNLOAD:
        return await this.executeOfflineDownloadTask(task);
      default:
        throw new Error(`未知的任务类型: ${task.type}`);
    }
  }

  // 执行下载任务
  async executeDownloadTask(task) {
    const { filePath, fileName } = task.data;

    try {
      // 导入下载API
      const { getDownloadInfo } = await import("../js/cloudApi.js");

      // 获取下载信息
      task.updateProgress(10);
      const downloadInfo = await getDownloadInfo(filePath);

      if (task.cancelled) {
        throw new Error("任务已取消");
      }

      task.updateProgress(50);

      // 使用window.open打开下载链接
      window.open(downloadInfo.download_url, "_blank");

      task.updateProgress(100);
      return { success: true, message: "下载链接已打开" };
    } catch (error) {
      throw new Error(`下载失败: ${error.message || "未知错误"}`);
    }
  }

  // 执行上传任务
  async executeUploadTask(task) {
    const { file, targetPath } = task.data;

    try {
      // 导入上传API
      const { uploadFileWithType } = await import("../js/cloudApi.js");

      // 更新任务信息，显示文件名
      task.data.fileName = file.name;
      task.data.fileSize = file.size;

      // 开始上传
      task.updateProgress(10);

      // 执行上传
      const result = await uploadFileWithType(targetPath, file, false);

      if (task.cancelled) {
        throw new Error("任务已取消");
      }

      task.updateProgress(100);
      return {
        success: true,
        message: `${file.name} 上传完成`,
        result,
        fileName: file.name,
        fileSize: file.size,
      };
    } catch (error) {
      throw new Error(`${file.name} 上传失败: ${error.message || "未知错误"}`);
    }
  }

  // 执行删除任务
  async executeDeleteTask(task) {
    const { filePath } = task.data;

    try {
      // 导入删除API
      const { deleteItem } = await import("../js/cloudApi.js");

      task.updateProgress(50);

      // 调用删除API
      await deleteItem(filePath, false); // 不显示成功通知，由任务队列处理

      if (task.cancelled) {
        throw new Error("任务已取消");
      }

      task.updateProgress(100);
      return { success: true, message: "删除完成" };
    } catch (error) {
      throw new Error(`删除失败: ${error.message || "未知错误"}`);
    }
  }

  // 执行重命名任务
  async executeRenameTask(task) {
    const { oldPath, newName } = task.data;

    try {
      // 导入重命名API
      const { renameItem } = await import("../js/cloudApi.js");

      // 构建新路径
      const pathParts = oldPath.split("/");
      pathParts.pop(); // 移除文件名
      const directory = pathParts.join("/");
      const newPath = directory + "/" + newName;

      task.updateProgress(50);

      // 调用重命名API
      await renameItem(oldPath, newPath, false); // 不显示成功通知，由任务队列处理

      if (task.cancelled) {
        throw new Error("任务已取消");
      }

      task.updateProgress(100);
      return { success: true, message: "重命名完成", newPath };
    } catch (error) {
      throw new Error(`重命名失败: ${error.message || "未知错误"}`);
    }
  }

  // 执行创建文件夹任务
  async executeCreateFolderTask(task) {
    const { folderName, targetPath } = task.data;

    try {
      // 导入创建目录API
      const { createDirectory } = await import("../js/cloudApi.js");

      // 更新任务信息
      task.data.fileName = folderName;

      // 开始创建
      task.updateProgress(10);

      // 调用创建目录API
      const result = await createDirectory(targetPath, folderName, false);

      if (task.cancelled) {
        throw new Error("任务已取消");
      }

      task.updateProgress(100);
      return {
        success: true,
        message: `文件夹 ${folderName} 创建成功`,
        result,
        fileName: folderName,
        fileInfo: result.file_info,
      };
    } catch (error) {
      throw new Error(
        `创建文件夹 ${folderName} 失败: ${error.message || "未知错误"}`
      );
    }
  }

  // 执行移动任务
  async executeMoveTask(task) {
    const { sourcePath, targetPath } = task.data;

    // 这里应该调用实际的移动API
    return new Promise((resolve) => {
      setTimeout(() => {
        task.updateProgress(100);
        resolve({ success: true, message: "移动完成" });
      }, 800);
    });
  }

  // 执行复制任务
  async executeCopyTask(task) {
    const { sourcePath, targetPath } = task.data;

    // 这里应该调用实际的复制API
    return new Promise((resolve) => {
      let progress = 0;
      const interval = setInterval(() => {
        if (task.cancelled) {
          clearInterval(interval);
          return;
        }

        if (task.paused) {
          return;
        }

        progress += Math.random() * 20;
        if (progress >= 100) {
          progress = 100;
          clearInterval(interval);
          task.updateProgress(progress);
          resolve({ success: true, message: "复制完成" });
        } else {
          task.updateProgress(progress);
        }
      }, 400);
    });
  }

  // 执行离线下载任务
  async executeOfflineDownloadTask(task) {
    const { url, path, filename } = task.data;

    try {
      // 导入离线下载API
      const { createOfflineDownload } = await import("../js/cloudApi.js");

      // 更新任务信息
      task.data.fileName = filename;

      // 开始下载
      task.updateProgress(10);

      // 调用离线下载API
      const result = await createOfflineDownload(url, path, filename, false);

      if (task.cancelled) {
        throw new Error("任务已取消");
      }

      task.updateProgress(100);
      return {
        success: true,
        message: `${filename} 离线下载任务已创建`,
        result,
        fileName: filename,
        fileInfo: result.file_info,
      };
    } catch (error) {
      throw new Error(
        `${filename} 离线下载失败: ${error.message || "未知错误"}`
      );
    }
  }

  // 事件监听器管理
  on(event, callback) {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, []);
    }
    this.eventListeners.get(event).push(callback);
  }

  off(event, callback) {
    if (this.eventListeners.has(event)) {
      const listeners = this.eventListeners.get(event);
      const index = listeners.indexOf(callback);
      if (index > -1) {
        listeners.splice(index, 1);
      }
    }
  }

  emit(event, data) {
    console.log(`触发事件: ${event}`, data?.id, data?.status);
    if (this.eventListeners.has(event)) {
      this.eventListeners.get(event).forEach((callback) => {
        try {
          callback(data);
        } catch (error) {
          console.error(`事件监听器错误 (${event}):`, error);
        }
      });
    }
  }

  // 获取队列统计信息
  getStats() {
    const allTasks = this.getAllTasks();
    const stats = {
      total: allTasks.length,
      pending: 0,
      running: 0,
      completed: 0,
      failed: 0,
      cancelled: 0,
      paused: 0,
      byType: {},
      byPriority: {},
    };

    allTasks.forEach((task) => {
      stats[task.status]++;

      if (!stats.byType[task.type]) {
        stats.byType[task.type] = 0;
      }
      stats.byType[task.type]++;

      if (!stats.byPriority[task.priority]) {
        stats.byPriority[task.priority] = 0;
      }
      stats.byPriority[task.priority]++;
    });

    return stats;
  }
}

// 创建全局任务队列实例
const taskQueue = new TaskQueue();

// 导出
export default taskQueue;
export { Task, TaskQueue };
